import requestApi from "@/util/request";
import type { RegisterType } from "@/types/register.ts";
import { InnerDecode, ModbusFunctionCode } from "@/types/register.ts";

export async function addSlave(deviceName: string, slaveId: number): Promise<boolean> {
  try {
    return await requestApi(`/slave/add_slave`, 'post', {
      "device_name": deviceName,
      "slave_id": slaveId,
    });
  } catch (error) {
    return false;
  }
}

export async function deleteSlave(deviceName: string, slaveId: number): Promise<boolean> {
  try {
    return await requestApi(`/slave/delete_slave`, 'post', {
      "device_name": deviceName,
      "slave_id": slaveId,
    });
  } catch (error) {
    return false;
  }
}

export async function getSlaveIdList(deviceName: string): Promise<any> {
  try {
    return await requestApi(`/slave/get_slave_id_list`, 'post', {
      "device_name": deviceName
    });
  } catch (error) {
    return [];
  }
}

export async function setSlaveAddress(deviceName: string, slaveId: number, registerType: number, startAddress: number,
  endAddress: number): Promise<boolean> {
  try {
    return requestApi(`/slave/set_slave_address`, 'post', {
      "device_name": deviceName,
      "register_type": registerType,
      "slave_id": slaveId,
      "start_address": startAddress,
      "end_address": endAddress
    });
  } catch (error) {
    return false;
  }
}

export async function getSlaveTable(deviceName: string, slaveId: number, registerType: number): Promise<any> {
  try {
    return await requestApi(`/slave/get_slave_table`, 'post', {
      "device_name": deviceName,
      "slave_id": slaveId,
      "register_type": registerType,
    });
  } catch (error) {
    return [];
  }
}

export async function readRegister(deviceName: string, slaveId: number, registerType: number, startAddress: number,
  endAddress: number): Promise<any> {
  try {
    return await requestApi(`/slave/read_register`, 'post', {
      "device_name": deviceName,
      "register_type": registerType,
      "slave_id": slaveId,
      "start_address": startAddress,
      "end_address": endAddress
    });
  } catch (error) {
    return false;
  }
}

export async function writeRegister(deviceName: string, slaveId: number, registerType: RegisterType, startAddress: number,
  data_type: InnerDecode, value_list: number[], write_func: ModbusFunctionCode): Promise<any> {
  try {
    return await requestApi(`/slave/write_register`, 'post', {
      "device_name": deviceName,
      "slave_id": slaveId,
      "register_type": registerType,
      "start_address": startAddress,
      "data_type": data_type,
      "value_list": value_list,
      "write_func": write_func
    });
  } catch (error) {
    return false;
  }
}
